<template>
	<view style="background-color: #fff;border-radius: 5vw;box-shadow: 0 0 0.1vw 0 #ccc; height: 900rpx;" >
		<view class="wanl-share">
			<view class="wanl-share-header">
				<view class="head" style="display: flex;justify-content: space-between;align-items: center;" >
					<view class="content"><view class="text-lg">分享</view></view>
					<!-- <view class="footer" @tap="close"><text>取消</text></view> -->
					<view class="close wlIcon-31guanbi" @tap="close"></view>
				</view>
				<view>
					<uv-tabs :current="current" :list="productData" lineColor="#fd8c00" :activeStyle="{
						color: '#fd8c00',
					}" :scrollable="false" @click="toAnchor"></uv-tabs>
				</view>
			</view>
		
			<scroll-view class="scroll-x solid-bottom" scroll-x="true" show-scrollbar="false" :scroll-left="scrollAnimation" scroll-with-animation>
				<!-- #ifdef MP -->
				<!-- <view class="scroll-item">
					<button open-type="share">
						<view class="icons bg-green"><text class="wlIcon-31fenxiang"></text></view>
						<view class="project text-sm"><text>分享</text></view>
					</button>
				</view> -->
				<!-- #endif -->
				<view class="scroll-item" v-for="(value, index) in providerList" :key="index" v-if="value" @tap="share(value)">
					<view class="icons" :class="value.background"><text :class="value.icon"></text></view>
					<view class="project text-sm">
						<text>{{ value.name }}</text>
					</view>
				</view>
				
				<canvas class="qrcode-canvas" canvas-id="qrcode" style="width: 200px; height: 200px;" />
				<view class="page-container">
					<view class="content">
						<view class="poster-image"><image v-if="posterSrc" :src="posterSrc" mode="aspectFit"></image></view>
						<canvas class="poster-canvas" canvas-id="poster" :style="{ width: `${postercanvas_width}px`, height: `${postercanvas_height}px` }" />
					</view>
				</view>
			</scroll-view>
			
			<view class="foot padding-lr-bj" style="padding: 10rpx 0;">
				<button v-if="current == 0" class="cu-btn round text-bold complete text-white" style="border:1rpx solid #fd8c00; background-color: #ffffff; color: #fd8c00; width: 338rpx; height: 68rpx;">保存图片</button>
				<button v-if="current == 1" class="cu-btn round text-bold complete text-white" style="border:1rpx solid #fd8c00; background-color: #ffffff; color: #fd8c00; width: 338rpx; height: 68rpx;" @tap.stop="share({ id: 'link' })">复制链接</button>
				<button v-if="current == 0 || current == 1" class="cu-btn round text-bold complete text-white" style="background-color: #fd8c00; width: 338rpx; height: 68rpx; margin-left: 24rpx;">立即分享</button>
				<button v-if="current == 2" class="cu-btn round text-bold complete text-white" style="background-color: #fd8c00; width: 338rpx; height: 68rpx;">复制并分享</button>
			</view>
		</view>
	</view>
</template>

<script>
	/**
	 * WanlShare 分享 
	 * @description 分享组件 深圳前海万联科技有限公司 https://www.wanlshop.com（除万联官方内嵌系统，未经授权严禁使用）
	 * @著作权：WanlShop 登记号：2020SR0255711 版本：V1.0.0
	 * @property {Number} scrollAnimation 滚动位置
	 * @property {Number} shareType 分享类型 0.图文 1.纯文字 2.纯图片 5.小程序
	 * @property {String} shareTitle 分享标题
	 * @property {String} shareText 分享详情
	 * @property {String} image 分享图片 如果是图文分享，且是ios平台，20kb
	 * @property {String} href 分享链接
	 * @event {Function} change 关闭弹窗
	 * @example <wanl-share :scrollAnimation="scrollAnimation" shareTitle="" shareText="" image="" href="" @change="hideModal"/>
	 */
	import uQRCode from '@/common/uqrcode.js';
	export default {
		name: 'WanlShare',
		props: {
			scrollAnimation: {
				type: Number,
				default: 300
			},
			shareType: {
				type: Number,
				default: 0
			},
			shareTitle: {
				type: String,
				default: ''
			},
			shareText: {
				type: String,
				default: ''
			},
			image: {
				type: String,
				default: ''
			},
			href: {
				type: String,
				default: ''
			},
			isReport: {
				type: Boolean,
				default: false
			},
		},
		data() {
			return {
				providerList: [],
				current: 1,
				productData: [
					{
						name: "保存图片"
					},
					{
						name: "分享好友"
					},
					{
						name: "一键发圈"
					},
				],
				QRCodeText: '',
				QRCodeSrc: '',
				posterSrc: '',
				postercanvas_width: 0, // 画布宽度
				postercanvas_height: 0, // 画布高度
				posterTemplates: []
			};
		},
		created() {
			uni.getProvider({
				service: 'share',
				success: e => {
					let data = [];
					// #ifdef APP-PLUS
					for (let i = 0; i < e.provider.length; i++) {
						switch (e.provider[i]) {
							case 'weixin':
								data.push(
									{
										name: '微信好友',
										id: 'weixin',
										icon: 'wlIcon-WeChat',
										background: 'bg-green',
										sort: 0
									},
									{
										name: '微信朋友圈',
										id: 'weixin',
										icon: 'wlIcon-pengyouquan',
										background: 'bg-green',
										type: 'WXSenceTimeline',
										sort: 1
									}
								);
								break;
							case 'sinaweibo':
								data.push({
									name: '新浪微博',
									id: 'sinaweibo',
									icon: 'wlIcon-WeiBo',
									background: 'red',
									sort: 2
								});
								break;
							case 'qq':
								data.push({
									name: 'QQ',
									id: 'qq',
									icon: 'wlIcon-QQ',
									background: 'blue',
									sort: 3
								});
								break;
							default:
								break;
						}
					}
					// #endif
					data.push(
						{
							name: '生成海报',
							id: 'poster',
							icon: 'wlIcon-classify',
							background: 'gray',
							sort: 4
						}
					// 	{
					// 		name: '链接',
					// 		id: 'link',
					// 		icon: 'wlIcon-lianjie',
					// 		background: 'gray',
					// 		sort: 5
					// 	}
					// );
					// if(this.isReport){
					// 	data.push(
					// 		{
					// 			name: '举报',
					// 			id: 'report',
					// 			icon: 'wlIcon-jubao',
					// 			background: 'gray',
					// 			sort: 6
					// 		}
					);
					//}
					this.providerList = data.sort((x, y) => {
						return x.sort - y.sort;
					});
				},
				fail: e => {
					uni.showModal({
						content: '获取分享通道失败',
						showCancel: false
					});
				}
			});
			
			// 提示
			// uni.showLoading({
			// 	title: '二维码生成中',
			// 	mask: true
			// });
			this.QRCodeText = this.href;
			console.log("ddddddddddddddddddddd", this.QRCodeText);
			this.loadData();
		},
		mounted() {
			setTimeout(() => {
				this.toAnchor({ index: 0 })
			}, 2570)
		},
		methods: {
			async share(e) {
				if (e.id == 'poster') {
					this.$wanlshop.to('/pages/user/qrcode/qrcode?url='+encodeURIComponent(this.href));
				} else if (e.id == 'link') {
					this.$wanlshop.copy(this.href);
				} else if (e.id == 'report') {
					//this.complaint();
				} else {
					if (!this.shareTitle && (this.shareType === 1 || this.shareType === 0)) {
						uni.showModal({
							content: '分享内容不能为空',
							showCancel: false
						});
						return;
					}

					if (!this.image && (this.shareType === 2 || this.shareType === 0)) {
						uni.showModal({
							content: '分享图片不能为空',
							showCancel: false
						});
						return;
					}
					
					// 开始分享
					let shareOPtions = {
						provider: e.id,
						scene: e.type && e.type === 'WXSenceTimeline' ? 'WXSenceTimeline' : 'WXSceneSession', //WXSceneSession”分享到聊天界面，“WXSenceTimeline”分享到朋友圈，“WXSceneFavorite”分享到微信收藏     
						type: this.shareType,
						success: (e) => {
							uni.showModal({
								content: '已分享',
								showCancel:false
							})
						},
						fail: (e) => {
							uni.showModal({
								content: e.errMsg,
								showCancel:false
							})
						}
					}
					
					switch (this.shareType){
						case 0:
							shareOPtions.summary = this.shareText;
							shareOPtions.imageUrl = this.image;
							shareOPtions.title = this.shareTitle;
							shareOPtions.href = this.href;
							break;
						case 1:
							shareOPtions.summary = this.shareText;
							break;
						case 2:
							shareOPtions.imageUrl = this.image;
							break;
						case 5:
							var pages = getCurrentPages();  
							var page = (pages[pages.length - 1]).route;  
							shareOPtions.imageUrl = this.image ? this.image : $wanlshop.appstc('/qrcode/logo.png');
							shareOPtions.title = this.shareTitle;
							shareOPtions.miniProgram = {
								id: this.$store.state.common.appConfig.mp_weixin_id,
								path: page, //微信小程序ID
								webUrl: this.href,
								type:0
							};
							break;
						default:
							break;
					}
					// if(shareOPtions.type === 0 && plus.os.name === 'iOS'){//如果是图文分享，且是ios平台，则压缩图片 
					// 	shareOPtions.imageUrl = await this.compress();
					// }
					if(shareOPtions.type === 1 && shareOPtions.provider === 'qq'){//如果是分享文字到qq，则必须加上href和title
						shareOPtions.href = this.href;
						shareOPtions.title = this.shareTitle;
					}
					uni.share(shareOPtions);
				}
				this.close();
			},
			// 关闭模态框
			close() {
				this.$emit('change');
			},
			// 举报商品
			// complaint(){
			// 	this.$emit('change','complaint');
			// },
			// 切换tab
			toAnchor(val) {
				this.current = val.index;
			},
			// 二维码配置
			async loadData(option) {
				this.$api.post({
					url: '/wanlshop/common/qrcode',
					success: res => {
						// 下载到本地
						res.forEach((item, index, arr) => {
							if (item.template != 'wanlshopqr') {
								// 远程下载背景
								uni.downloadFile({
									url: this.$wanlshop.oss(item.background_url, 350, 0),
									success: e => {
										item.background_url = e.tempFilePath;
									}
								});
								// 远程下载图标
								uni.downloadFile({
									url: this.$wanlshop.oss(item.logo_src, 40, 40),
									success: e => {
										item.logo_src = e.tempFilePath;
									}
								});
							}
						});
						// 赋值
						this.posterTemplates = res;
						console.log("ddddddddddddddddddddddwwwwwwwwwwwww", this.posterTemplates);
						// if(res.length == 0){
						// 	uni.showModal({
						// 	    title: '重要提示',
						// 	    content: '平台尚未配置二维码，请到后台系统管理【配置二维码】',
						// 	    success: (r)=> {
						// 			this.$wanlshop.back(1);
						// 	    }
						// 	});
						// }else{
						// 	uni.showLoading({
						// 		title: '加载配置中',
						// 		mask: true
						// 	});
						// }
						this.create(this.posterTemplates[1]);
						// 生成二维码
						// uQRCode.make({
						// 	canvasId: 'qrcode',
						// 	text: this.QRCodeText,
						// 	size: 200,
						// 	success: res => {
						// 		console.log("wwwwwwwwwwwwwwwww", res);
						// 		this.QRCodeSrc = res;
						// 		// 默认生成第一张海报
						// 		this.create(this.posterTemplates[0]);
						// 	},
						// 	fail: err => {
						// 		console.log("ddddddddddddddddd", err);
						// 	}
						// });
					}
				});
			},
			create(posterTemplate) {
				if (posterTemplate.checked) {
					return;
				}
				// uni.showLoading({
				// 	title: '海报生成中',
				// 	mask: true
				// });
				this.posterTemplates.forEach(x => {
					x.checked = false;
				});
				posterTemplate.checked = true;
				
				console.log("ggggggggggggggggggggggggggggg", posterTemplate);
			
				this.postercanvas_width = posterTemplate.canvas_width;
				this.postercanvas_height = posterTemplate.canvas_height;
			
				this.posterSrc = '';
				setTimeout(() => {
					switch (posterTemplate.template) {
						case 'wanlshopqrlist001':
							this.wanlshopqrlist001({
								canvasId: 'poster',
								canvas_width: posterTemplate.canvas_width,
								canvas_height: posterTemplate.canvas_height,
								backgroundSrc: posterTemplate.background_url,
								logoSrc: posterTemplate.logo_src,
								name: this.$store.state.user.username,
								text: '长按扫描二维码~',
								QRCodeSrc: posterTemplate.logo_src,
								success: res => {
									console.log("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
									this.posterSrc = res;
									uni.hideLoading();
								}
							});
							break;
						case 'wanlshopqr':
							this.wanlshopqr({
								canvasId: 'poster',
								canvas_width: posterTemplate.canvas_width,
								canvas_height: posterTemplate.canvas_height,
								QRCodeSrc: this.QRCodeSrc,
								success: res => {
									this.posterSrc = res;
									uni.hideLoading();
								}
							});
							break;
					}
				}, 100);
			},
			save() {
				uni.saveImageToPhotosAlbum({
					filePath: this.posterSrc,
					success: () => {
						this.$wanlshop.msg('保存成功');
					}
				});
			},
			wanlshopqrlist001(options) {
				console.log("bbbbbbbbbbbbbbbbbbbbbwedddddd", options);
				let { canvas_width, canvas_height, backgroundSrc, logoSrc, name, text, QRCodeSrc } = options;
				// 绑定画布
				var ctx = uni.createCanvasContext(options.canvasId);
				// 清除画布
				ctx.clearRect(0, 0, canvas_width, canvas_height);
			
				// 获取背景图片信息
				let backgroundImageInfo = {
					width: '500',
					height: '667'
				};
				// 设置背景图片宽高
				let backgroundWidth = canvas_width;
				let backgroundHeight = (backgroundImageInfo.height * canvas_width) / backgroundImageInfo.width;
				// 填充背景图片
				ctx.drawImage(backgroundSrc, 0, 0, backgroundWidth, backgroundHeight);
				// 设置标志图片宽高坐标
				let logoWidth = 80;
				let logoHeight = 80;
				let logoX = 36;
				let logoY = backgroundHeight + (canvas_height - backgroundHeight) / 2 - logoHeight / 2;
				// 绘制为圆形标志
				ctx.save();
				ctx.beginPath();
				// 先画个圆  前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
				ctx.arc(logoWidth / 2 + logoX, logoHeight / 2 + logoY, logoWidth / 2, 0, Math.PI * 2, false);
				ctx.closePath();
				// 画好了圆 剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内 这也是我们要save上下文的原因
				ctx.clip();
				// 填充标志图片
				ctx.drawImage(logoSrc, logoX, logoY, logoWidth, logoHeight);
				// 恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制
				ctx.restore();
			
				// 名称最大长度限制 10，超出为省略号
				if (name.length > 10) {
					name = name.substring(0, 10) + '...';
				}
				// 计算文字定位距离
				let nameX = logoX + logoWidth + 10;
				let nameY = logoY + 32;
				let nameFontSize = 20;
				// 设置名称文字样式
				ctx.setFillStyle('#000000');
				ctx.setFontSize(nameFontSize);
				// 填充名称到画布
				ctx.fillText(name, nameX, nameY);
			
				// 计算文字定位距离
				let textX = nameX;
				let textY = nameY + 32;
				let textFontSize = 16;
				// 设置分享文案文字样式
				ctx.setFillStyle('#999999');
				ctx.setFontSize(textFontSize);
				// 填充分享文案到画布
				ctx.fillText(text, textX, textY);
			
				// 设置二维码图片宽高
				let QRCodeWidth = 100;
				let QRCodeHeight = 100;
				// 计算二维码图片定位距离
				let QRCodeX = canvas_width - QRCodeWidth - 36;
				let QRCodeY = backgroundHeight + (canvas_height - backgroundHeight) / 2 - QRCodeHeight / 2;
				// 填充二维码图片
				ctx.drawImage(QRCodeSrc, QRCodeX, QRCodeY, QRCodeWidth, QRCodeHeight);
			
				// 输出到画布中
				ctx.draw(false, () => {
					// 绘图全部完成后生成文件路径
					uni.canvasToTempFilePath({
						canvasId: options.canvasId,
						fileType: 'jpg',
						success: res => {
							console.log('hhhhhhhhhhhhhhhhhhhhhhhhhhhh', res);
							options.success && options.success(res.tempFilePath);
						}
					});
				});
			},
			wanlshopqr(options) {
				let { canvas_width, canvas_height, QRCodeSrc } = options;
				// 绑定画布
				var ctx = uni.createCanvasContext(options.canvasId);
				// 清除画布
				ctx.clearRect(0, 0, canvas_width, canvas_height);
				// 填充二维码图片，并设置边距
				ctx.drawImage(QRCodeSrc, 15, 15, canvas_width - 30, canvas_height - 30);
				// 输出到画布中
				ctx.draw(false, () => {
					// 绘图全部完成后生成文件路径
					uni.canvasToTempFilePath({
						canvasId: options.canvasId,
						fileType: 'jpg',
						success: res => {
							options.success && options.success(res.tempFilePath);
						}
					});
				});
			}
		}
	};
</script>
<style lang="scss">
	.wanl-share-header {
		background-color: #ffffff;
	}
	/* 分享 */
	.wanl-share {
		min-height: 50rpx;
		padding-bottom: 0px;
		padding-bottom: env(safe-area-inset-bottom);
	}
	.wanl-share .head {
		padding: 25rpx 25rpx 10rpx 25rpx;
	}
	.wanl-share .head .content {
		justify-content: left;
		//margin-left: 16rpx;
		width: 100%;
		font-weight: 700;
		color: #000000;
	}
	.wanl-share .scroll-x {
		white-space: nowrap;
		width: 100%;
		padding: 32rpx 0;
		text-align: left;
		height: 250rpx;
		background-color: #f6efe9;
	}
	.wanl-share .scroll-x .scroll-item {
		display: inline-block;
		font-size: 36rpx;
		margin-left: 36rpx;
		text-align: center;
	}

	.wanl-share .scroll-x .scroll-item button {
		line-height: 1;
		background-color: rgba(0, 0, 0, 0);
		border: 0;
		padding: 0;
	}

	.wanl-share .scroll-x .scroll-item button:after {
		border: 0;
	}

	.wanl-share .scroll-x .scroll-item:last-child {
		margin-right: 36rpx;
	}

	.wanl-share .scroll-x .scroll-item .icons {
		width: 100rpx;
		height: 100rpx;
		line-height: 100rpx;
		border-radius: 9999rpx;
		margin: 0 auto;
		font-size: 40rpx;
		display: block;
	}
	.wanl-share .scroll-x .scroll-item .icons.gray {
		color: #606060;
		background-color: #f5f5f5;
	}
	.wanl-share .scroll-x .scroll-item .icons.red {
		color: #ffffff;
		background-color: #e6162c;
	}
	.wanl-share .scroll-x .scroll-item .icons.blue {
		color: #ffffff;
		background-color: #3e92e8;
	}

	.wanl-share .scroll-x .scroll-item .project {
		margin-top: 25rpx;
	}
	.wanl-share .footer {
		height: 90rpx;
		line-height: 90rpx;
		font-size: 30rpx;
	}
	.solid-bottom {
		height: 654rpx !important;
		padding: 32rpx !important;
		margin-top: -5rpx;
	}
</style>
